// pages/Details/Details.js
const app = getApp()
var util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
      subject:{},
      checkpoint:0,
      pic:"",
      word1:{
        id:"",
        word:"",
        windex:""
      },
      word2:{
        id:"",
        word:"",
        windex:""
      },
      word3:{
        id:"",
        word:"",
        windex:""
      },
      word4:{
        id:"",
        word:"",
        windex:""
      },
      answer:"",
      Count:3,
      is_Count:false,
      CountDown:40,
      is_error:true,
      SuccessAnswered:0,
      currentpoint:0,
      is_Success:true
  },
    //关闭提示
    close:function () {
      this.setData({
          is_error:true
      })
        wx.navigateBack({
            delta: 1
        })
    },
    //广告跳转
    avdtap:function (e) {
        wx.navigateToMiniProgram({
            appId: e.currentTarget.dataset.appid,
            path: 'pages/index/index',
            success:function(res) {
                console.log(res)
            }
        })
    },
    //错了再来一次
    OnceMore:function () {
        var that = this
        that.resetChallengeObj();
        app.globalData.userInfo.frequency = app.globalData.userInfo.frequency+1
        that.update()
        that.setData({
            SuccessAnswered:0,
            currentpoint:0,
            is_error:true,
            Count:3,
            is_Count:false
        })
        //that.newData(that.data.data)
        //console.log("重新开始",e)
        that.onLoadWord(that.datachuli())
    },
    //闯关成功继续下一关
    OnceMore2:function () {
        var that = this
        app.globalData.userInfo.frequency = app.globalData.userInfo.frequency+1;
        that.update()
        that.setData({
            SuccessAnswered:0,
            currentpoint:that.data.currentpoint+1,
            is_Success:true,
            Count:3,
            is_Count:false
        })
        that.onLoadWord(that.datachuli())
    },
    ii:function () {
        clearInterval(this.Countimer);
    },
    //回答问题
  optionBindtap:function (e) {
      var that = this
      var opt = e.currentTarget.dataset
      var index = opt.index
      var data = that.data.option
      if(that.data.word1.id===""||that.data.word2.id===""||that.data.word3.id===""||that.data.word4.id===""){
      data[index].word = ''
      data[index].id = ''
      that.setData({
          option: data,
      })
        if(that.data.word1.id===""){
            that.setData({
                word1:{
                    id:e.currentTarget.dataset.id,
                    word:e.currentTarget.dataset.word,
                    windex:e.currentTarget.dataset.index
                }
            })
            }else if(that.data.word2.id===""){
                that.setData({
                    word2:{
                        id:e.currentTarget.dataset.id,
                        word:e.currentTarget.dataset.word,
                        windex:e.currentTarget.dataset.index
                    }
                })

            }
            else if(that.data.word3.id===""){
                that.setData({
                    word3:{
                        id:e.currentTarget.dataset.id,
                        word:e.currentTarget.dataset.word,
                        windex:e.currentTarget.dataset.index
                    }
                })
            }else{
                that.setData({
                    word4:{
                        id:e.currentTarget.dataset.id,
                        word:e.currentTarget.dataset.word,
                        windex:e.currentTarget.dataset.index
                    }
                })
           var word = that.data.word1.word+that.data.word2.word+that.data.word3.word+e.currentTarget.dataset.word
            console.log(word)
            clearInterval(that.Countimer);
            if(that.data.answer== word){
                that.music("/image/2.mp3")
                wx.showModal({
                    title: "回答正确",
                    content: "正确答案:"+word,
                    showCancel: false,
                    confirmText: "确定",
                    success: function(res) {
                        if (res.confirm) {
                            //console.log('用户点击确定')
                            if(that.data.SuccessAnswered<29){
                                that.setData({
                                    SuccessAnswered:that.data.SuccessAnswered+1
                                })
                                that.onLoadWord(that.data.newData)
                            }else{
                                that.music("/image/4.mp3")
                                clearInterval(that.Countimer);
                                app.globalData.userInfo.pass = app.globalData.userInfo.pass+1
                                that.setData({
                                    SuccessAnswered:0,
                                    currentpoint:that.data.currentpoint+1,
                                })
                                that.setData({
                                    is_Success:false
                                })
                                that.update()
                            }
                        } else if (res.cancel) {
                            //console.log('用户点击取消')
                        }
                    }
                })
            }else{
                that.music("/image/3.mp3")
                that.Refresh()
                setTimeout(function () {
                        that.setData({
                            is_error:false
                        })
                    }
                    ,500)
                /*wx.showToast({
                    title: '回答错误!',
                    image: '/image/errIcon.png',
                    duration: 2000
                })*/
            }
        }
    }
  },
  // 下一题
  onLoadWord:function (e) {
       // console.log(e)
        var that = this
        //app.innerAudioContext.pause()
        that.setData({
            word1:{
                id:"",
                word:""
            },
            word2:{
                id:"",
                word:""
            },
            word3:{
                id:"",
                word:""
            },
            word4:{
                id:"",
                word:""
            },
            CountDown: 40,
        })
        that.Count()
        var data = e
        /*var a = parseInt(that.data.currentpoint/10)
        var b = that.data.currentpoint%10*/
        var c = that.data.SuccessAnswered
        function randomSort(a, b) {
            return Math.random() > 0.5 ? -1 : 1;
        }
        var op = []
        var option =[]
        console.log(data,data[c])
        op = data[c].word.split("");
        for(var i=0;i<op.length;i++){
            var h = {id:i,word:op[i]}
            option.push(h)
        }
        option = option.sort(randomSort);
        var subject = data[c]
        that.setData({
            option2:option,
            option:option,
            subject:data[c],
            pic:data[c].pic,
            answer:data[c].answer
        })
    },
  //修改答案
  answerWord:function (e) {
      //console.log(e.currentTarget,e.currentTarget.dataset)
     var that = this
      var opt = e.currentTarget.dataset
      var index = opt.windex
      var data = that.data.option
      data[index].word = e.currentTarget.dataset.word
      data[index].id = e.currentTarget.dataset.id
      that.setData({
          option: data
      })
      if(e.currentTarget.dataset.type == 1){
          that.setData({
              word1:{
                  id:"",
                  word:""
              }
          })
      }else if(e.currentTarget.dataset.type == 2){
          that.setData({
              word2:{
                  id:"",
                  word:""
              }
          })
      }else if(e.currentTarget.dataset.type ==3){
          that.setData({
              word3:{
                  id:"",
                  word:""
              }
          })
      }else{


      }

  },
  update:function () {
        var that = this
        var NewTime = new Date().getTime().toString();
        console.log(app.globalData.userInfo.userid,NewTime,app.globalData.userInfo.frequency,app.globalData.userInfo.pass,app.globalData.userInfo.userid)
        var key = util.sha1(app.globalData.userInfo.userid + NewTime + app.globalData.userInfo.frequency + app.globalData.userInfo.pass + app.globalData.userInfo.userid);
        key = key.toUpperCase()
        var data = {}
        console.log('update群场景shareTicket:',app.globalData)
        var update = function (data) {
            wx.request({
                url: 'https://caige1.sanliwenhua.com/program/update_rank?app=7',
                method: "post",
                data: data,
                success: function (res) {
                    console.log(res)
                    //app.globalData.group_id = res.data.group_id;
                },
                fail: function (res) {
                    console.log(res)
                    wx.showToast({
                        title: res.data.message,
                        icon: 'success',
                        duration: 2000
                    })
                }
            })
        }
        if(app.globalData.shareTicket){
            wx.getShareInfo({
                shareTicket:app.globalData.shareTicket,
                success:function (res) {
                    console.log(res)
                    app.globalData.Sharing= {}
                    app.globalData.Sharing.errMsg = res.errMsg
                    app.globalData.Sharing.encryptedData = res.encryptedData
                    app.globalData.Sharing.iv = res.iv
                    console.log(app.globalData.Sharing)
                    data = {
                        key: key,
                        time: NewTime,
                        pass: app.globalData.userInfo.pass,
                        frequency:app.globalData.userInfo.frequency,
                        x_token: app.globalData.userInfo.token,
                        errMsg: res.errMsg,
                        encryptedData: res.encryptedData,
                        iv: res.iv,
                        session_key: app.globalData.userInfo.session_key
                    }
                    update(data);
                },
                fail:function (res) {
                    wx.showToast({
                        title: res.data.message,
                        icon: 'success',
                        duration: 2000
                    })
                }
            })
        }else{
            data = {
                key: key,
                time: NewTime,
                pass: app.globalData.userInfo.pass,
                frequency:app.globalData.userInfo.frequency,
                x_token: app.globalData.userInfo.token
            }
            update(data);
        }
    },
  //重置答案
  Refresh:function(){
       this.setData({
           word1:{
               id:"",
               word:""
           },
           word2:{
               id:"",
               word:""
           },
           word3:{
               id:"",
               word:""
           },
           word4:{
               id:"",
               word:""
           },
           option:this.data.option2
       })
   },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      var that = this
      that.resetChallengeObj()
      app.globalData.userInfo.frequency = app.globalData.userInfo.frequency+1
      that.update()
      console.log(app.globalData.userInfo)
          that.setData({
              userInfo:app.globalData.userInfo
          })
      that.onLoadWord(that.datachuli())
      that.adver()
  },
    datachuli:function () {
        var that = this
        var easyData=[]
        //console.log(app.globalData)
        function getRandomArrayElements(arr, count) {
            var shuffled = arr, i = arr.length, min = i - count, temp, index;
            while (i-- > min) {
                index = Math.floor((i + 1) * Math.random());
                temp = shuffled[index];
                shuffled[index] = shuffled[i];
                shuffled[i] = temp;
            }
            return shuffled.slice(min);
        }
        var easyData = getRandomArrayElements(app.globalData.easy, 15)
        //console.log(easyData)
        var middleData = easyData.concat(getRandomArrayElements(app.globalData.middle, 10))
        //console.log(middleData)
        var hardData = middleData.concat(getRandomArrayElements(app.globalData.hard, 5))
        //console.log(hardData)
        that.setData({
            newData:hardData
        })
        return hardData
    },
    dete:function (e) {
        var that = this
        var dataItemList = []
        var newData = []
        var dataList = []
        function randemList(a, b) {
            return Math.random()>0.5?1:-1
        }
        e.map(function (item, index) {
            item.id = parseInt(item.id)
            if (index % 300 != 0) {
                dataItemList.push(item)
            } else {
                if (index > 0) {
                    dataItemList.sort(randemList)
                    dataList = that.newDataList(dataItemList)
                    newData.push(dataList)
                }
                dataItemList = [item]
            }
            return item
        })
        dataList = that.newDataList(dataItemList)
        newData.push(dataList)
        that.setData({
            newData:newData
        })
        return newData
    },
    newData:function (e) {
        var that = this
        var dataItemList = []
        var newData = []
        function randemList(a, b) {
            return Math.random()>0.5?1:-1
        }
        for(var i=0;i<e.length;i++){
            e[i].sort(randemList)
            newData.push(e[i])
        }
        newData.sort(randemList)
        console.log("重组的数据",newData,e)
        that.setData({
            data:newData
        })
    },
    newDataList:function (e) {
        var that = this
        var dataItemList = []
        var newData = []
        function randemList(a, b) {
            return Math.random()>0.5?1:-1
        }
        for(var i=0;i<e.length;i++){
            //e[i].sort(randemList)
            if(i%30!=0){
                dataItemList.push(e[i])
            }else{
                if (i > 0) {
                    dataItemList.sort(randemList)
                    newData.push(dataItemList)
                }
                dataItemList = [e[i]]
            }
        }
        newData.push(dataItemList)
        console.log("300个重组成10个",newData,e)
        return newData
    },

    //处理减去挑战机会
    resetChallengeObj:function () {
        var that = this
        var myTime = new Date();
        var today = myTime.getDate();
        wx.getStorage({
            key: 'ChallengeObj',
            success: function (res) {
                var ChallengeObj = JSON.parse(res.data)
                //console.log('ChallengeObj', ChallengeObj)
                if (today = ChallengeObj.day) {
                    if(ChallengeObj.ChallengeTime>0){
                        var ChallengeTime = ChallengeObj.ChallengeTime-1
                        ChallengeObj = {
                            day: today,
                            ChallengeTime: ChallengeTime
                        }
                    }
                }else{
                    ChallengeObj = {
                        day: today,
                        ChallengeTime: 3
                    }
                }
                wx.setStorage({
                    key: 'ChallengeObj',
                    data: JSON.stringify(ChallengeObj)
                })
                app.globalData.ChallengeObj = ChallengeObj
                console.log(app.globalData.ChallengeObj)
                that.setData({
                    ChallengeTime:ChallengeObj.ChallengeTime
                })

            }, fail: function (res) {
                //console.log(res)
                var ChallengeObj = {
                    day: today,
                    ChallengeTime: 3
                }
                wx.setStorage({
                    key: 'ChallengeObj',
                    data: JSON.stringify(ChallengeObj)
                })
                app.globalData.ChallengeObj = ChallengeObj
                that.setData({
                    ChallengeTime:ChallengeObj.ChallengeTime
                })
            }
        })
    },
    //闯关机会处理添加
    AddresetChallengeObj:function () {
        var that = this
        var myTime = new Date();
        var today = myTime.getDate();
        wx.getStorage({
            key: 'ChallengeObj',
            success: function (res) {
                var ChallengeObj = JSON.parse(res.data)
                //console.log('ChallengeObj', ChallengeObj)
                if (today != ChallengeObj.day) {
                    ChallengeObj = {
                        day: today,
                        ChallengeTime: 3
                    }
                }else{
                    ChallengeObj = {
                        day: today,
                        ChallengeTime: ChallengeObj.ChallengeTime+1
                    }
                }
                wx.setStorage({
                    key: 'ChallengeObj',
                    data: JSON.stringify(ChallengeObj)
                })
                app.globalData.ChallengeObj = ChallengeObj
                that.setData({
                    ChallengeTime:ChallengeObj.ChallengeTime
                })

            }, fail: function (res) {
                //console.log(res)
                var ChallengeObj = {
                    day: today,
                    ChallengeTime: 3
                }
                wx.setStorage({
                    key: 'ChallengeObj',
                    data: JSON.stringify(ChallengeObj)
                })
                app.globalData.ChallengeObj = ChallengeObj
                that.setData({
                    ChallengeTime:ChallengeObj.ChallengeTime
                })
            }
        })

    },
    music:function (e) {
        app.innerAudioContext = wx.createInnerAudioContext()
        app.innerAudioContext.autoplay = true
        app.innerAudioContext.src = e
    },
    //倒计时答题
  Count:function () {
      var that = this
        function count () {
          if(that.data.Count > 1){
              var Count = that.data.Count-1
              that.setData({
                  Count:Count
              })
          }else{
              clearInterval(timer);
              that.setData({
                  is_Count:true
              })
              that.CountDown()
          }
        }
        var timer = setInterval(count,1000);
      if(that.data.Count > 1){
          that.music("/image/1.mp3")
      }

    },
    //答题倒计时
  CountDown:function () {
        var that = this
        clearInterval(that.Countimer);
        that.Countimer = setInterval(function() {
            if(that.data.CountDown > 1){
                var CountDown = that.data.CountDown - 1
                that.setData({
                    CountDown:CountDown
                })
            }else{
                clearInterval(that.Countimer);
                that.setData({
                    is_error:false
                })
            }
        },1000);
    },
    //广告请求接口
  adver:function () {
      var that = this
      wx.request({
          url: 'https://caige1.sanliwenhua.com/program/column?app=7',
          method: "get",
          success: function (res) {
              //console.log(res, "广告")
              if (res.data.code = 200) {
                  var data = res.data.data;
                  var AdvData = []
                  var gameData=[]
                  for(var i = 0;i<data.length;i++){
                      if(data[i].type=="advs"){
                          AdvData.push(data[i])
                      }
                  }
                  for(var i = 0;i<data.length;i++){
                      if(data[i].type=="game"){
                          gameData.push(data[i])
                      }
                  }
                  console.log(AdvData,gameData)
                  that.setData({
                      avdUrl: AdvData,
                      gameData:gameData
                  })
              }
          }
      })
        /*wx.request({
            url: 'https://caige1.sanliwenhua.com/switch',
            method: "get",
            success: function (res) {
                //console.log(res, "开关")
                if (res.data.code = 200) {
                    var isADV = res.data.data.isADV;
                    that.setData({
                        isADV: isADV //广告开关写死
                    })
                } else {

                }
            }
        })*/

    },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
      wx.showShareMenu({
          withShareTicket: true
      })
  },
    getShare:function (e,a) {
        var that = this
        var data = {}
        wx.getShareInfo({
            shareTicket:e,
            success:function (res) {
                console.log(res)
                data = {
                    x_token: app.globalData.userInfo.token,
                    encryptedData: res.encryptedData,
                    iv: res.iv,
                }
                console.log("传递的参数:",data)
                wx.request({
                    url: 'https://caige1.sanliwenhua.com/program/shars?app=7',
                    method: "get",
                    data: data,
                    success: function (res) {
                        console.log("分享返回:",res.data.message)
                        if(res.data.code==200){
                            if(a =="qiuzhu"){
                                wx.showModal({
                                    title: "求助成功!",
                                    content: "正确答案:"+that.data.answer,
                                    showCancel: false,
                                    confirmText: "确定"
                                })
                            }else{
                                that.setData({
                                    SuccessAnswered:0,
                                    currentpoint:0,
                                    is_error:true
                                })
                                that.AddresetChallengeObj()
                                wx.navigateBack({
                                    delta: 1
                                })
                                //that.onLoadWord(that.data.data)
                            }
                        }else{
                            wx.showModal({
                                title: "提示",
                                content: "要分享到不一样的群才可以哦",
                                showCancel: false,
                                confirmText: "确定"
                            })
                        }
                    },
                    fail: function (res) {
                        console.log(res)
                        wx.showToast({
                            title: res.data.message,
                            icon: 'success',
                            duration: 2000
                        })
                    }
                })
            },
            fail:function (res) {
                wx.showToast({
                    title: res.data.message,
                    icon: 'success',
                    duration: 2000
                })
            }
        })
    },
    /**
     * 用户点击右上角分享
     */
  onShareAppMessage: function (e) {
        var that = this;
        var nickeName = app.globalData.userInfo.nickName;
        console.log(e)
        if (e.from === 'button') {
            if(e.target.dataset.type == "qiuzhu"){
                return {
                    title: '['+nickeName+'@我],那些年学过的成语，还记得吗？快来挑战吧！',
                    path: 'pages/index/index',
                    //imageUrl: 'http://paz0eiqln.bkt.clouddn.com/image/fenxing2.jpg',
                    success: function (res) {
                        console.log('分享到群的标记',res.shareTickets)
                        if(res.shareTickets){
                            that.getShare(res.shareTickets[0],e.target.dataset.type)
                        }else{
                            wx.showModal({
                                title: "提示",
                                content: "分享到微信群才可以获得求助哦！",
                                showCancel: false,
                                confirmText: "确定"
                            })
                        }
                    },
                    fail: function (res) {
                        wx.showToast({
                            title: '分享失败！',
                            image: '/image/errIcon.png',
                            duration: 2000
                        })
                    }
                }
            }
            if(e.target.dataset.type == "tiaozhan"){
                return {
                    title: '['+nickeName+'@我],那些年学过的成语，还记得吗？快来挑战吧！',
                    path: 'pages/index/index',
                    imageUrl: 'http://paz0eiqln.bkt.clouddn.com/image/fenxing2.jpg',
                    success: function (res) {
                        console.log('分享到群的标记', res)
                        if(res.shareTickets){
                            that.getShare(res.shareTickets[0],e.target.dataset.type)
                        }else{
                            wx.showModal({
                                title: "提示",
                                content: "分享成功！分享到微信群才可以获取挑战机会哦！",
                                showCancel: false,
                                confirmText: "确定"
                            })
                        }
                    },
                    fail: function (res) {
                        wx.showToast({
                            title: '分享失败！',
                            image: '/image/errIcon.png',
                            duration: 2000
                        })
                    }
                }

            }
            if(e.target.dataset.type == "xuanyao"){
                return {
                    title: '['+nickeName+'@我],那些年学过的成语，还记得吗？快来挑战吧！',
                    path: 'pages/index/index',
                    imageUrl: 'http://paz0eiqln.bkt.clouddn.com/image/fenxing2.jpg',
                    success: function (res) {
                        wx.showToast({
                            title: '分享成功！',
                            icon: 'success',
                            duration: 2000
                        })
                    },
                    fail: function (res) {
                        wx.showToast({
                            title: '分享失败！',
                            image: '/image/errIcon.png',
                            duration: 2000
                        })
                    }
                }

            }

        }else{
            return {
                title: '['+nickeName+'@我],那些年学过的成语，还记得吗？快来挑战吧！',
                path: 'pages/index/index',
                imageUrl: 'http://paz0eiqln.bkt.clouddn.com/image/fenxing2.jpg',
                success: function (res) {
                    wx.showToast({
                        title: '分享成功!',
                        icon: 'success',
                        duration: 2000
                    })
                },
                fail: function (res) {
                    wx.showToast({
                        title: '分享失败！',
                        image: '/image/errIcon.png',
                        duration: 2000
                    })
                }
            }

        }


    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },


})